﻿using System;
using System.Text;

namespace XBee.Communications
{
    public abstract class CommunicationData : ICommunicationData
    {
        #region Members
        private byte byteStartDelimiter = 33;
        private byte byteFinishDelimiter = 63;
        private byte parameterDelimiter = 15;
        private string version = "1.0.0";
        #endregion

        #region Properties
        public byte ByteStartDelimiter
        {
            get { return byteStartDelimiter; }
            set { byteStartDelimiter = value; }
        }
        public byte ByteFinishDelimiter
        {
            get { return byteFinishDelimiter; }
            set { byteFinishDelimiter = value; }
        }
        public byte ParameterDelimiter
        {
            get { return parameterDelimiter; }
            set { parameterDelimiter = value; }
        }
        public string Version
        {
            get { return version; }
            set { version = value; }
        }
        #endregion

        #region Methods
        public abstract string Serialize();
        public abstract ICommunicationData CreateInstance(string sentence);
        public virtual string RemoveDelimiters(string sentence)
        {
            string res = sentence;
            int inicio = res.LastIndexOf((char)this.ByteStartDelimiter) + 1;
            int fin = res.LastIndexOf((char)this.ByteFinishDelimiter) - 1;

            res = sentence.Substring(inicio, fin);
            return res;
        }
        public virtual bool IsSecuenceComplete(byte[] tempData)
        {
            bool res = false;
            int index = 0;
            while (!res && index < tempData.Length)
            {
                if (tempData[index] == this.ByteStartDelimiter)
                {
                    while (!res && index < tempData.Length)
                    {
                        if (tempData[index] == this.ByteFinishDelimiter)
                        {
                            res = true;
                            break;
                        }
                        else
                            index++;
                    }
                    break;
                }
                else
                    index++;
            }
            return res;
        } 
        #endregion
    }
}
